package wodegua.d29_多线程;

import java.util.concurrent.*;

/**
 * 掌握线程池的创建
 */
public class d7_ThreadPoolExecutorCallable {
    public static void main(String[] args) throws Exception {
        ExecutorService pool = new ThreadPoolExecutor(3,5,8, TimeUnit.SECONDS, new ArrayBlockingQueue<>(3)
                , Executors.defaultThreadFactory(), new ThreadPoolExecutor.AbortPolicy());

        //执行 Callable 任务
//        Future<String> p1 = pool.submit(new MyCallablePool(100));
//        Future<String> p2 = pool.submit(new MyCallablePool(200));
//        Future<String> p3 = pool.submit(new MyCallablePool(300));
//        Future<String> p4 = pool.submit(new MyCallablePool(400));
//        Future<String> p5 = pool.submit(new MyCallablePool(500));

        System.out.println(pool.submit(new MyCallablePool(100)).get());
        System.out.println(pool.submit(new MyCallablePool(200)).get());
        System.out.println(pool.submit(new MyCallablePool(300)).get());
        System.out.println(pool.submit(new MyCallablePool(400)).get());
        System.out.println(pool.submit(new MyCallablePool(500)).get());
        System.out.println(pool.submit(new MyCallablePool(600)).get());
        System.out.println(pool.submit(new MyCallablePool(700)).get());
    }
}

class MyCallablePool implements Callable<String> {
    private final int n;

    public MyCallablePool(int n) {
        this.n = n;
    }

    @Override
    public String call() throws Exception {
        //求1-n的和
        int sum = 0;
        for (int i = 1; i <= n; i++) {
            sum += i;
        }
        return Thread.currentThread().getName() + "执行1-" + n + "的和=" + sum;
    }
}
